package com.hgzy.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hgzy.sys.common.*;
import com.hgzy.sys.domain.Permission;
import com.hgzy.sys.domain.User;
import com.hgzy.sys.service.PermissionService;
import com.hgzy.sys.vo.PermissionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜单页面的前端控制器
 * @author : look-word
 * @date : 2022-01-15 09:14
 **/
@RestController
@RequestMapping("menu")
public class MenuController {
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("loadIndexLeftMenuJson")
    public DataGridView loadIndexLeftMenuJson(HttpSession session){
        // 查询所有菜单
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("type", Constant.TYPE_MENU);
        wrapper.eq("available",Constant.TYPE_TRUE);
        List<Permission> list = null;
        // 判断当前用户有哪些菜单
        ActiveUser activeUser=(ActiveUser)session.getAttribute("user");
        // session取出当前用户
        User user = activeUser.getUser();
        // 判断当前是否是管理员
        if (user.getType().equals(Constant.USER_TYPE_SUPER)){
            list=permissionService.list(wrapper);
        }else {
            // 根据id+角色+权限去查
            list=permissionService.list(wrapper);
        }
        // 拼接页面的层级关系
        List<TreeNode> treeNodes=new ArrayList<>();
        for (Permission permission : list) {
             Integer id=permission.getId();
             Integer pid=permission.getPid();
             String  icon=permission.getIcon();
             String  title=permission.getTitle();
             String  href=permission.getHref();
             boolean  spread= permission.getOpen() == 1;
            treeNodes.add(new TreeNode(id,pid,icon,title,href,spread));
        }
        List<TreeNode> build = TreeNodeBuilder.build(treeNodes, 1);

        return new DataGridView(build);
    }
}
